/*
 * utils.c
 *
 *  Created on: 2011-11-8
 *      Author: zhangtao
 */
#include <gl_utils.h>

#include <math.h>
void calculateNormal(GLfloat normal[], GLfloat vertexes[9]){
	GLfloat x0 = vertexes[3] - vertexes[0];
	GLfloat y0 = vertexes[4] - vertexes[1];
	GLfloat z0 = vertexes[5] - vertexes[2];
	GLfloat x1 = vertexes[6] - vertexes[3];
	GLfloat y1 = vertexes[7] - vertexes[4];
	GLfloat z1 = vertexes[8] - vertexes[5];
	GLfloat x2 = y0 * z1 - z0 * y1;
	GLfloat y2 = z0 * x1 - x0 * z1;
	GLfloat z2 = x0 * y1 - y0 * x1;
	GLdouble length = sqrt(x2 * x2 + y2 * y2 + z2 * z2);
	normal[0] = x2 / length;
	normal[1] = y2 / length;
	normal[2] = z2 / length;
}
void createShadowMatrix(GLfloat matrix[16], GLfloat planeEq[4], GLfloat light[3]){
	float a = planeEq[0];
	float b = planeEq[1];
	float c = planeEq[2];
	float d = planeEq[3];

	float lx = light[0];
	float ly = light[1];
	float lz = light[2];

	matrix[0] = b * ly + c * lz;
	matrix[1] = -a * ly;
	matrix[2] = -a * lz;
	matrix[3] = 0.0;

	matrix[4] = -b * lx;
	matrix[5] = a * lx + c * lz;
	matrix[6] = -b * lz;
	matrix[7] = 0.0;

	matrix[8] = -c * lx;
	matrix[9] = -c * ly;
	matrix[10] = a * lx + b * ly;
	matrix[11] = 0.0;

	matrix[12] = -d * lx;
	matrix[13] = -d * ly;
	matrix[14] = -d * lz;
	matrix[15] = a * lx + b * ly + c * lz;

}
void crossProduct(GLfloat result[3], GLfloat vecter1[3], GLfloat vecter2[3]){
	result[0] = vecter1[1] * vecter2[2] - vecter1[2] * vecter2[1];
	result[1] = vecter1[2] * vecter2[0] - vecter1[0] * vecter2[2];
	result[2] = vecter1[0] * vecter2[1] - vecter1[1] * vecter2[0];
}
void createPlaneEquation(GLfloat equ[4], GLfloat vertexes[9]){
	calculateNormal(equ, vertexes);
	equ[3] = -(equ[0] * vertexes[0] + equ[1] * vertexes[1] + equ[2] * vertexes[2]);
}
